<?php
    // +----------------------------------------------------------------------
    // | Created by PHPstorm: JRKAdmin框架 [ JRKAdmin ]
    // +----------------------------------------------------------------------
    // | Copyright (c) 2019~2022 [LuckyHHY] All rights reserved.
    // +----------------------------------------------------------------------
    // | SiteUrl: http://www.luckyhhy.cn
    // +----------------------------------------------------------------------
    // | Author: LuckyHhy <jackhhy520@qq.com>
    // +----------------------------------------------------------------------
    // | Date: 2020/1/13-9:21
    // +----------------------------------------------------------------------
    // | Description:  
    // +----------------------------------------------------------------------


    namespace app\admin\model;


    use app\admin\imple\Comm;
    use app\common\model\BaseModel;
    use Qiniu\Auth;
    use Qiniu\Storage\UploadManager;
    use think\facade\Request;
    use think\Image;

    class Uploads extends BaseModel implements Comm
    {

        // 设置数据表
        protected $table =DB_PREFIX."upload";

        protected $setting;

        protected function initialize()
        {
            parent::initialize(); // TODO: Change the autogenerated stub

            $this->setting=model("settings")->getSetting();
        }


        /**
         * @param $id
         * @return bool|mixed
         * @author: LuckyHhy <jackhhy520@qq.com>
         * @date: 2020/2/25
         * @name: del
         * @describe:删除
         */
        public function del($id)
        {
           //dump($id);
            try {
                $info=self::where('id', 'in', $id)->select()->toArray();
                if (empty($info)){
                    $this->error("删除失败");
                }
                foreach($info as $K){
                    @unlink($K['file_path']); //删除原件
                }
                $del = self::destroy(['id' => ['in', $id]]);
                $del?$this->success("删除成功"):$this->error("删除失败");

            } catch (\Exception $exception) {

                $this->error($exception->getMessage());
            }
        }


        /**
         * @param array $param
         * @param string $order
         * @return mixed|\think\Paginator
         * @throws \think\exception\DbException
         * @author: LuckyHhy <jackhhy520@qq.com>
         * @date: 2020/2/29 0029
         * @name: getAdminPageData
         * @describe：获取分页数据
         */
        public function getAdminPageData($param = [], $order = 'id asc')
        {
            // TODO: Implement getAdminPageData() method.
            $where = [];
            $page  = 75;
            if(!empty($param)) {
                //搜索条件
                if(!empty($param['filename'])) {
                    $where[] = ['filename','like', "%".$param['filename']."%"];
                }
                isset($param['page_size']) && $param['page_size']!=0 ? $page = (int)$param['page_size'] : 1;
            }
            $data = self::where($where)->order($order)->paginate($page);
            return $data;
        }


        /**
         * @param int $page
         * @return \think\Paginator
         * @throws \think\exception\DbException
         * @author: LuckyHhy <jackhhy520@qq.com>
         * @date: 2020/3/1 0001
         * @name: GetImagesFiles
         * @describe：获取图片文件素材
         */
        public function GetImagesFiles($type=1,$page=21){

            if ($type==1){
                $ext=['png','jpeg','jpg','gif'];
            }else{
                $ext=['zip','rar','pdf','txt','doc','docx','ppt','xls','xlsx','mp3','mp4'];
            }

            $data = self::where('ext','in',$ext)->order("create_time desc")->paginate($page);

            return $data;
        }

        /**
         * @param $data
         * @return mixed|void
         * @author: LuckyHhy <jackhhy520@qq.com>
         * @date: 2020/1/10
         * @name: addAndEdit
         * @describe:
         */
        public function addAndEdit($data)
        {
            // TODO: Implement addAndEdit() method.
            return parent::doAll($data);
        }


        /**
         * @param $width
         * @param $height
         * @param string $filePath
         * @param string $name
         * @return array
         * @author: LuckyHhy <jackhhy520@qq.com>
         * @date: 2020/1/13
         * @name: uploadThumb
         * @describe:上传缩略图
         */
        public function uploadThumb($width, $height, $filePath = "t_images", $name = "file")
        {
           // $file = request()->file($name);
            $file=Request::file($name);
            if($file) {
                $filePaths = ROOT_PATH.'public'.DS_PROS.'uploads'.DS_PROS.$filePath;
                $info      = $file->validate(['size' => $this->setting['size'], 'ext' => $this->setting['ext']])->move($filePaths);
                if($info) {
                    $md5       = $file->hash('md5');
                    $sha1      = $file->hash('sha1');
                    $imgpath   = 'uploads/'.$filePath.'/'.$info->getSaveName();
                    $image     = Image::open($imgpath);
                    $date_path = 'uploads/'.$filePath.'/thumb/'.date('Ymd');
                    if(!file_exists($date_path)) {
                        mkdir($date_path, 0777, true);
                    }
                    $thumb_path = $date_path.'/'.$info->getFilename();
                    $image->thumb($width, $height)->save($thumb_path);

                    @unlink(ROOT_PATH.'public'.DS_PROS.$imgpath);//删除原有上传的图片

                    //$arr   = ['file_size' => $info->getSize(),  'up_type' => $this->setting['upload_type'], 'ext' => $info->getExtension(), 'create_time' => time(), 'filename' => $file->getInfo('name'), 'file_path' => '/'.$thumb_path, 'file_md5' => $md5, 'file_sha1' => $sha1, 'suffix' => $info->getType()];
                   // $getid = $this->saveUpload($arr);
                    return ['code' => 1, 'msg' => "上传成功", 'save_id' => '', 'thumb' => "", 'path' => '/'.$thumb_path, 'savename' => $info->getSaveName(), 'filename' => $info->getFilename(), 'info' => $info->getInfo(), 'ext' => $info->getExtension()];
                }
                else {
                    // 上传失败获取错误信息
                    return ['code' => 0, 'msg' => $file->getError()];
                }
            }
        }


        /**
         * @param $type
         * @param string $filename
         * @param bool $is_water
         * @param int $width
         * @param int $height
         * @return array
         * @throws \Exception
         * @author: LuckyHhy <jackhhy520@qq.com>
         * @date: 2020/3/4
         * @name: upFileNoSave
         * @describe:不保存到数据库
         */
        public function upFileNoSave($type, $filename = 'file', $is_water = false, $width = 200, $height = 400)
        {
            // 获取表单上传文件 例如上传了001.jpg
            $file=Request::file($filename);

            //先检测MD5和哈希是否存储过
            $md5   = $file->hash('md5');
            $sha1  = $file->hash('sha1');
          /*  $is_up = $this->checkFileIsUp($md5, $sha1, $this->setting['upload_type']);

            if($is_up!==true) {
                //上传过了
                $is_up['code']         = 1;
                $is_up['msg']          = '上传成功';
                $is_up['info']['name'] = $file->getInfo('name');
                return $is_up;
            }*/

            //type 2 七牛  3 oss  1 本地
            if($this->setting['upload_type']==2) {
                //七牛云存储
                $tmp_name=$file->getInfo('tmp_name');   //临时目录
                //文件后缀
                $ext = pathinfo($file->getInfo('name'), PATHINFO_EXTENSION);

                // 构建一个鉴权对象
                $auth =new Auth(GetSysConfig('qiniu_access_key'),GetSysConfig('qiniu_secret_key'));
                // 生成上传的token
                $token = $auth->uploadToken(GetSysConfig('qiniu_bucket'));
                // 上传到七牛后保存的文件名
                $up_file_name=date('Ymd') . '/' . md5($tmp_name . time().mt_rand(0,9999));
                $key = $up_file_name . '.' .$ext;

                // 初始化UploadManager类
                $uploadMgr = new UploadManager();
                list($ret,$err) = $uploadMgr->putFile($token,$key,$tmp_name);
                if($err !== null){
                    return array('code'=>0,'msg'=>$err);
                }else{
                    $file_path=GetSysConfig('qiniu_domain') . '/' . $key;
                    //保存上传历史
                    $arr=['file_size'=>$file->getInfo('size'),'create_time'=>time(),'filename'=>$file->getInfo('name'),'file_path'=>$file_path,'file_md5'=>$md5,'file_sha1'=>$sha1,'suffix'=>$file->getInfo('type'),'up_type'=>2];
                    $this->saveUpload($arr);
                    return array('code'=>200,'msg'=>'上传成功','path'=>$file_path,'savename'=>$up_file_name,'filename'=>$file->getInfo('name'),'info'=>$file->getInfo());

                }
            }
            else if($this->setting['upload_type']==3) {
                //oss
                return ['code' => 0, 'msg' => '上传方式不存在'];
            }
            else {
                // 移动到框架应用根目录/uploads/ 目录下
                $info = $file->validate(['size' => $this->setting['size'], 'ext' => $this->setting['ext']])->move(ROOT_PATH.'public'.DS_PROS.'uploads'.DS_PROS.$type);
                //$info = $file->move(ROOT_PATH . 'public' . DS . 'uploads' . DS . $type);
                if($info) {
                    $path = '/uploads'.DS_PROS.$type.DS_PROS.$info->getSaveName();
                    //如果需要添加水印
                    /*$setting = cache('settings');
                    if($is_water && $setting['is_watermark'] && $setting['watermark'] && $type = 'images' ){
                        $image = \think\Image::open(ROOT_PATH . $path);
                        if($image->width() >= $setting['watermark_width'] && $image->height() >= $setting['watermark_height']){
                            $image->water(ROOT_PATH . $setting['watermark'],$setting['watermark_locate'],$setting['watermark_alpha'])->save(ROOT_PATH . $path);
                        }
                    }*/
                    $path = str_replace("\\", "/", $path);

                    return ['code' => 1, 'msg' => '上传成功', 'save_id' => 0, 'path' => $path, 'savename' => $info->getSaveName(), 'filename' => $info->getFilename(), 'info' => $info->getInfo(), 'ext' => $info->getExtension()];
                }
                else {
                    return ['code' => 0, 'msg' => $file->getError()];
                }
            }

        }

        /**
         * @param $type
         * @param string $filename
         * @param bool $is_water
         * @param int $width
         * @param int $height
         * @return array|bool
         * @throws \think\db\exception\DataNotFoundException
         * @throws \think\db\exception\ModelNotFoundException
         * @throws \think\exception\DbException
         * @author: LuckyHhy <jackhhy520@qq.com>
         * @date: 2020/1/13
         * @name: upfile
         * @describe: 上传文件
         */
        public function upfile($type, $filename = 'file', $is_water = false, $width = 200, $height = 400)
        {
            // 获取表单上传文件 例如上传了001.jpg
            $file=Request::file($filename);

            //先检测MD5和哈希是否存储过
            $md5   = $file->hash('md5');
            $sha1  = $file->hash('sha1');
            $is_up = $this->checkFileIsUp($md5, $sha1, $this->setting['upload_type']);

            if($is_up!==true) {
                //上传过了
                $is_up['code']         = 1;
                $is_up['msg']          = '上传成功';
                $is_up['info']['name'] = $file->getInfo('name');
                return $is_up;
            }

            //type 2 七牛  3 oss  1 本地
            if($this->setting['upload_type']==2) {
                    //七牛云存储
                    $tmp_name=$file->getInfo('tmp_name');   //临时目录
                    //文件后缀
                    $ext = pathinfo($file->getInfo('name'), PATHINFO_EXTENSION);
                    $config = $this->setting['qiniu_config'];
                    // 构建一个鉴权对象
                    $auth =new Auth($config['accessKey'],$config['secretKey']);
                    // 生成上传的token
                    $token = $auth->uploadToken($config['bucket']);
                    // 上传到七牛后保存的文件名
                    $up_file_name=date('Ymd') . '/' . md5($tmp_name . time().mt_rand(0,9999));
                    $key = $up_file_name . '.' .$ext;

                    // 初始化UploadManager类
                    $uploadMgr = new UploadManager();
                    list($ret,$err) = $uploadMgr->putFile($token,$key,$tmp_name);
                    if($err !== null){
                        return array('code'=>0,'msg'=>$err);
                    }else{
                        $file_path=$config['domain'] . '/' . $key;
                        //保存上传历史
                        $arr=['file_size'=>$file->getInfo('size'),'create_time'=>time(),'filename'=>$file->getInfo('name'),'file_path'=>$file_path,'file_md5'=>$md5,'file_sha1'=>$sha1,'suffix'=>$file->getInfo('type'),'up_type'=>2];
                        $this->saveUpload($arr);
                        return array('code'=>200,'msg'=>'上传成功','path'=>$file_path,'savename'=>$up_file_name,'filename'=>$file->getInfo('name'),'info'=>$file->getInfo());

                    }
            }
            else if($this->setting['upload_type']==3) {
                return ['code' => 0, 'msg' => '上传方式不存在'];
            }
            else {
                // 移动到框架应用根目录/uploads/ 目录下
                $info = $file->validate(['size' => $this->setting['size'], 'ext' => $this->setting['ext']])->move(ROOT_PATH.'public'.DS_PROS.'uploads'.DS_PROS.$type);
                //$info = $file->move(ROOT_PATH . 'public' . DS . 'uploads' . DS . $type);
                if($info) {
                    $path = '/uploads'.DS_PROS.$type.DS_PROS.$info->getSaveName();
                    //如果需要添加水印
                    /*$setting = cache('settings');
                    if($is_water && $setting['is_watermark'] && $setting['watermark'] && $type = 'images' ){
                        $image = \think\Image::open(ROOT_PATH . $path);
                        if($image->width() >= $setting['watermark_width'] && $image->height() >= $setting['watermark_height']){
                            $image->water(ROOT_PATH . $setting['watermark'],$setting['watermark_locate'],$setting['watermark_alpha'])->save(ROOT_PATH . $path);
                        }
                    }*/
                    $path = str_replace("\\", "/", $path);


                    //保存上传历史
                    $arr   = ['file_size' => $info->getSize(),  'up_type' => $this->setting['upload_type'], 'ext' => $info->getExtension(), 'create_time' => time(), 'filename' => $file->getInfo('name'), 'file_path' => $path, 'file_md5' => $md5, 'file_sha1' => $sha1, 'suffix' => $info->getType()];
                    $getid = $this->saveUpload($arr);
                    return ['code' => 1, 'msg' => '上传成功', 'save_id' => $getid, 'path' => $path, 'savename' => $info->getSaveName(), 'filename' => $info->getFilename(), 'info' => $info->getInfo(), 'ext' => $info->getExtension()];
                }
                else {
                    return ['code' => 0, 'msg' => $file->getError()];
                }
            }

        }



        /**
         * @param $type
         * @param string $filename
         * @return false|string
         * @throws \think\db\exception\DataNotFoundException
         * @throws \think\db\exception\ModelNotFoundException
         * @throws \think\exception\DbException
         * @author: LuckyHhy <jackhhy520@qq.com>
         * @date: 2020/3/9
         * @name: upvideo
         * @describe:上传视频
         */
        public function upvideo($type, $filename = 'file'){
            // 获取表单上传文件 例如上传了001.jpg
            $file=Request::file($filename);

            //先检测MD5和哈希是否存储过
            $md5   = $file->hash('md5');
            $sha1  = $file->hash('sha1');
            $is_up = $this->checkFileIsUp($md5, $sha1, $this->setting['upload_type']);

            if($is_up!==true) {
                //上传过了
                $is_up['code']         = 1;
                $is_up['msg']          = '上传成功';
                $is_up['info']['name'] = $file->getInfo('name');
                echo json_encode($is_up);
            }

            // 移动到框架应用根目录/uploads/ 目录下
            $info = $file->validate(['size' => 1024*1024*900, 'ext' => $this->setting['ext']])->move(ROOT_PATH.'public'.DS_PROS.'uploads'.DS_PROS.$type);
            //$info = $file->move(ROOT_PATH . 'public' . DS . 'uploads' . DS . $type);
            if($info) {
                $path = '/uploads'.DS_PROS.$type.DS_PROS.$info->getSaveName();

                $path = str_replace("\\", "/", $path);

                //保存上传历史
                $arr   = ['file_size' => $info->getSize(),  'up_type' => $this->setting['upload_type'], 'ext' => $info->getExtension(), 'create_time' => time(), 'filename' => $file->getInfo('name'), 'file_path' => $path, 'file_md5' => $md5, 'file_sha1' => $sha1, 'suffix' => $info->getType()];
                $getid = $this->saveUpload($arr);

                $arrs= ['code' => 1, 'msg' => '上传成功', 'save_id' => $getid, 'path' => $path, 'savename' => $info->getSaveName(), 'filename' => $info->getFilename(), 'info' => $info->getInfo(), 'ext' => $info->getExtension()];

                echo json_encode($arrs) ;
            }
            else {
                $arrs = ['code' => 0, 'msg' => $file->getError()];

                echo  json_encode($arrs);
            }

        }




        /**
         * @param $md5
         * @param $sha1
         * @param $type
         * @return array|bool
         * @throws \think\db\exception\DataNotFoundException
         * @throws \think\db\exception\ModelNotFoundException
         * @throws \think\exception\DbException
         * @author: hhygyl <hhygyl520@qq.com>
         * @name: checkFileIsUp
         * @describe:根据文件MD5和哈希值判断文件是否上传过
         */
        public function checkFileIsUp($md5, $sha1, $type)
        {
            $file_data = $this->where(['file_md5' => $md5, 'file_sha1' => $sha1, 'up_type' => $type])->find();
            if(empty($file_data)) {
                return true;
            }
            else {
                return ['path' => $file_data['file_path'], 'info' => ['name' => $file_data['filename'], 'size' => $file_data['file_size'],'save_id'=>$file_data['id'], 'type' => $file_data['suffix']]];
            }
        }

        /**
         * @param $arr
         * @return int|string
         * @author: hhygyl <hhygyl520@qq.com>
         * @name: saveUpload
         * @describe:保存到表里
         */
        public function saveUpload($arr)
        {
            return $this->insertGetId($arr);
        }








    }